import { useState, useEffect } from 'react'
import Loading from '@/components/ui/loading'
import { Pager } from '@/components/ui/pager'
import { Battle } from '@/types/battle'
import { battleRecord } from '@/apis/battle'
import { getSelfIpNum } from '@/apis/file'
import { BattleRow } from './BattleRow'

export default function BattleList() {
  const [battles, setBattles] = useState<Battle[]>([])
  const [isPageLoading, setIsPageLoading] = useState(false) // 翻页 loading
  const [error, setError] = useState<string | null>(null)
  const [selfIp, setSelfIp] = useState<number | null>(null)
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const pageSize = 10

  // 页码变化时请求数据（包括首次加载和翻页）
  useEffect(() => {
    const fetchBattles = async () => {
      // 首次加载或翻页都显示 loading
      setIsPageLoading(true)

      try {
        const data = await battleRecord({
          desc: ['created_at'],
          page,
          size: pageSize
        })
        if (data) {
          setBattles(data.items || [])
          setTotal(data.total || 0)
        } else {
          setError('Failed to fetch battles')
        }
      } catch (err) {
        setError('Error loading battles')
        console.error(err)
      } finally {
        setIsPageLoading(false)
      }
    }
    fetchBattles()
  }, [page])

  // 获取IP
  useEffect(() => {
    const fetchSelfIP = async () => {
      const ip = await getSelfIpNum()
      if (ip !== 0 && ip !== undefined) {
        setSelfIp(ip)
      }
    }
    fetchSelfIP()
  }, [])

  if (error) {
    return (
      <div className="mx-auto w-full max-w-4xl p-4">
        <div className="rounded border border-red-400 bg-red-100 px-4 py-3 text-red-700 dark:bg-red-900 dark:text-red-200">
          {error}
        </div>
      </div>
    )
  }

  return (
    <div
      className="relative mx-auto w-full max-w-3xl"
      style={{
        overflowX: 'hidden',
        boxShadow: '0 1px 16px 0 rgba(0,0,0,0.06)',
        minHeight: '400px'
      }}
    >
      {isPageLoading && (
        <div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-white/60 dark:bg-gray-900/60">
          <Loading />
        </div>
      )}
      {battles.length === 0 ? (
        <div className="py-6 text-center text-sm text-gray-400">
          暂无Battle记录
        </div>
      ) : (
        <>
          {/* 小屏 */}
          <div className="block md:hidden">
            {battles.map((battle, idx) => (
              <div
                key={idx}
                className={
                  `text-sm transition-colors duration-150 relative ` +
                  (idx % 2 === 0
                    ? 'bg-gradient-to-r from-blue-50 via-gray-100 to-blue-100 dark:from-gray-900 dark:via-gray-800 dark:to-blue-950'
                    : 'bg-gradient-to-r from-white via-gray-50 to-blue-50 dark:from-gray-800 dark:via-gray-900 dark:to-blue-900') +
                  ' hover:bg-blue-100 dark:hover:bg-blue-900 cursor-pointer ' +
                  (battle.created_ip !== selfIp
                    ? 'whitespace-normal break-words'
                    : '')
                }
              >
                <div
                  style={
                    battle.created_ip !== selfIp
                      ? { wordBreak: 'break-all', whiteSpace: 'normal' }
                      : {}
                  }
                >
                  <BattleRow battle={battle} selfIp={selfIp} />
                </div>
                <div className="pointer-events-none absolute inset-x-4 bottom-0 h-px bg-gray-200 opacity-70 dark:bg-gray-700" />
              </div>
            ))}
          </div>

          {/* 大屏 */}
          <div className="hidden md:block">
            {battles.map((battle, idx) => (
              <div
                key={battle.path}
                className={
                  `text-sm flex items-center transition-colors duration-150 relative ` +
                  (idx % 2 === 0
                    ? 'bg-gradient-to-r from-blue-50 via-gray-100 to-blue-100 dark:from-gray-900 dark:via-gray-800 dark:to-blue-950'
                    : 'bg-gradient-to-r from-white via-gray-50 to-blue-50 dark:from-gray-800 dark:via-gray-900 dark:to-blue-900') +
                  ' hover:bg-blue-100 dark:hover:bg-blue-900 cursor-pointer ' +
                  (battle.created_ip !== selfIp
                    ? 'whitespace-normal break-words'
                    : '')
                }
              >
                <div
                  style={
                    battle.created_ip !== selfIp
                      ? {
                          wordBreak: 'break-all',
                          whiteSpace: 'normal',
                          width: '100%'
                        }
                      : { width: '100%' }
                  }
                >
                  <BattleRow battle={battle} selfIp={selfIp} />
                </div>
                <div className="pointer-events-none absolute inset-x-4 bottom-0 h-px bg-gray-200 opacity-70 dark:bg-gray-700" />
              </div>
            ))}
          </div>

          {/* 分页 */}
          {total > pageSize && (
            <div className="mt-4">
              <Pager
                page={page}
                total={total}
                pageSize={pageSize}
                isPageLoading={isPageLoading}
                onPageChange={(p) => {
                  setPage(p)
                }}
              />
            </div>
          )}
        </>
      )}
    </div>
  )
}
